
#include <iostream>
#include <vector>
#include<queue>
#include <pthread.h>
#include "Thread.hpp"
#include "Log.hpp"
#include "Task.hpp"

using namespace ThreadModule;

const static int gdefaultthreadnum = 3;

template<typename T>
class ThreadPool
{

private:
    void LockQueue()
    {
        pthread_mutex_lock(&_mutex);
    }

    void UnlockQueue()
    {
        pthread_mutex_unlock(&_mutex);
    }

    void ThreadSleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }

    void ThreadWakeup()
    {
        pthread_cond_signal(&_cond);
    }

    void ThreadWakeupAll()
    {
        pthread_cond_broadcast(&_cond);
    }

public:
    ThreadPool(int threadnum = gdefaultthreadnum)
    :_threadnum(threadnum),
    _waitnum(0),
    _isrunning(false)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
        LOG(INFO,"ThreadPool Construct");
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

    void HandlerTask(std::string name)//包含 this指针
    {
        LOG(INFO, "%s is runnning...", name.c_str());
        while(true)
        {
            // 1. 保证队列安全
            LockQueue();

            // 2. 队列中不一定有数据
            while (_task_queue.empty() && _isrunning)
            {
                _waitnum++; 
                ThreadSleep();
                _waitnum--;
            }

            // 2.1 如果线程池已经退出了 && 任务队列是空的
            if (_task_queue.empty() && !_isrunning)
            {
                UnlockQueue();
                break;
            }
            // 2.2 如果线程池不退出 && 任务队列不是空的
            // 2.3 如果线程池已经退出 && 任务队列不是空的 --- 处理完所有的任务，然后在退出
          
            // 3. 一定有任务, 处理任务
            T t = _task_queue.front();
            _task_queue.pop();
            UnlockQueue();
            LOG(DEBUG, "%s get a task", name.c_str());
            
            // 4. 处理任务，这个任务属于线程独占的任务
            t();
            LOG(DEBUG, "%s handler a task, result is: %s", name.c_str(), t.ResultToString().c_str());           
        }

    }


    void InitThreadPool()
    {
        // 指向构建出所有的线程，并不启动
        for (int num = 0; num < _threadnum; num++)
        {
            std::string name = "thread-" + std::to_string(num + 1);
            //_threads.emplace_back(Print, name);
            _threads.emplace_back(std::bind(&ThreadPool::HandlerTask, this, std::placeholders::_1), name);
            LOG(INFO, " int thread %s done", name.c_str());
        }
        _isrunning = true;
    }

    void Start()
    {
        for(auto &thread : _threads)
        {
            thread.Start();
        }

    }

    void Stop()
    {
        LockQueue();
        _isrunning = false;
        ThreadWakeupAll();
        UnlockQueue();
    }


    bool Enqueue(const T &t)
    {
        bool ret = false;
        LockQueue();
        if(_isrunning)
        {
            _task_queue.push(t);
            if(_waitnum > 0)
            {
                ThreadWakeup();
            }
            LOG(DEBUG, "enqueue task success");

            ret = true;
        }

        UnlockQueue();
        return ret;
    }

    void Wait()
    {
        for(auto &thread : _threads)
        {
            thread.Join();
            LOG(INFO, "%s is quite...", thread.name().c_str());
        }

    }


private:
    int _threadnum;
    std::vector<Thread> _threads;
    std::queue<T> _task_queue;
    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    bool _isrunning;

    int _waitnum;
};